<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\model\OrderProduct;
use app\common\model\PolicyRelation;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 设备调拨
 *
 * @icon fa fa-circle-o
 */
class Allocation extends Backend
{

    /**
     * Allocation模型对象
     * @var \app\common\model\Allocation
     */
    protected $model = null;

    protected $company = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Allocation;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("fromTypeList", $this->model->getFromTypeList());
        $this->view->assign("toTypeList", $this->model->getToTypeList());
        $this->view->assign("dataTypeList", $this->model->getDataTypeList());
        $this->view->assign("confirmTypeList", $this->model->getConfirmTypeList());

        $this->company = $this->auth->getCompany();
        $this->assignconfig("company_id",$this->auth->id == 1 ? 0:$this->company->id);
        if(!$this->auth->isSuperAdmin()){
            $this->view->assign("company_id", $this->company->id);
        }
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $companyId = $this->auth->isSuperAdmin() && $this->auth->getGroupIds()[0] == 1 ? 0 : $this->auth->getCompany()->id;

            $list = $this->model
                ->where($where)
                ->whereOr(function ($query) use ( $companyId ){
                    $query->where(["to_type"=>1,"to"=>$companyId]);
                })
                ->whereOr(function ($query) use ( $companyId ){
                    $query->where(["from_type"=>1,"from"=>1]);
                })
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','type','from_type','from','to_type','to','to_text','policy_id','number','confirm_type','product_id','confirm_time','create_time',"order_id"]);
                $product = Lib::getProductById($row->product_id);
                if($product){
                    $row->product = $product['name'];
                }
                if($row->to_type == 1){
                    if($row->to > 0){
                        $obj = Lib::getCompany($row->to);
                        $row->to_text = $obj->name;
                    }else{
                        $row->to_text = "admin";
                    }
                }else if($row->to_type == 2) {
                    $obj = Lib::getUserInfo($row->to);
                    $row->to_text = $obj->nickname;
                }else{
                    $row->to = "暂无信息";
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        $from = $this->request->get('from',"normal");
        $orderProductId = $this->request->get('order_product');

        if (false === $this->request->isPost()) {

            if($from == "order"){
                $product = Db::name("order_product")->alias("a")->join("product p","p.id = a.product_id")
                    ->where(['a.id' => $orderProductId])->field("p.*,a.user_id")->find();
                $this->view->assign("product",$product);
            }else{
                if($this->auth->isSuperAdmin()){
                    $productList = \app\common\model\Product::where(["status" => 1])->select();
                }else{
                    $productList = Lib::getUserProduct(1,$this->auth->getCompany()->id);
                }
                $this->view->assign("product_list",$productList);
            }
            $this->view->assign("from",$from);
            $this->view->assign("company_id", $this->auth->isSuperAdmin() ? 0 :$this->company->id);
            $this->view->assign("group", $this->auth->getGroupIds()[0]);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['product_id'] = $params['product'];

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if($params['type'] == 1){
                if($params['to_type'] == 1){
                    $to = $params['to_company'];
                }else if($params['to_type'] == 2){
                    $to = $params['to_sale'];
                }
                if($to == "" || $to == 0){
                    $this->error("未选择接收人！");
                }
            }elseif ($params['type'] == 2){
                $company = Lib::getCompany($this->company->id);
                $params['to_type'] = 1;
                $to = $company->pid;
            }
            $params['to'] = $to;

            $list = [];
            if($params['data_type'] == 1){
                $fileData = Tools::importExcel($params['file_url']);
                $params['number'] = count($fileData) - 1;
                for($i = 1;$i < count($fileData);$i++){
                    $list[] = [
                        "sn" => trim($fileData[$i][0])
                    ];
                }
            }elseif ($params['data_type'] == 2){
                $snList =explode("\r\n",$params['sn']);
                array_pop($snList);
                array_unique($snList);
                $params['number'] = count($snList);
                foreach ($snList as $key => $val){
                    $list[] = [
                        "sn" => $val
                    ];
                }
                $params['sn'] = implode(",",$snList);
            }

            if(count($list) > 0){
                if ($from == "order"){
                    $orderProduct = OrderProduct::get($orderProductId);
                    if(count($list) != $orderProduct->number){
                        $this->error("调拨数量与订单不符！");
                    }
                    if($orderProduct->status != 0){
                        $this->error("订单该产品已调拨！");
                    }
                    $params['type_enum'] = $from;
                    $params['order_id'] = $orderProduct->order_id;
                    $orderProduct->status = 2;
                    $orderProduct->save();

                    $order = \app\common\model\Order::get($orderProduct->order_id);
                    if($order->pay_state == 1){
                        $order->pay_state = 2;
                        $order->save();
                    }
                }

            }else{
                $this->error("缺少调拨设备");
            }

            $params["from_type"] = 1;
            $params["from"] = $this->auth->id;
            $params["confirm_type"] = 1;
            $params["confirm_time"] = time();
            $result = $this->model->allowField(true)->save($params);
            $data = [];
            foreach ($list as $key => $val){
                $data[] = [
                    "allocation_id" => $this->model->id,
                    "sn" => $val['sn']
                ];
            }

            //保存调拨明细
            $details = new \app\common\model\AllocationDetails();
            $details->saveAll($data);

            //更新设备归属
            Tools::updateEquip($params['product'],$data,$params['to_type'],$params['to']);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function detail($ids){
        $row = $this->model->get($ids);

        $list = [];
        if($row->confirm_type == 1){
            $data = Lib::getAllocationDetails($row->id);
            foreach ($data as $key => $val){
                $list[] = ["sn" => $val->sn];
            }
        }else{
            if($row->data_type == 1){
                $fileData = Tools::importExcel($row->file_url);
                for($i = 1;$i < count($fileData);$i++){
                    $list[] = [
                        "sn" => $fileData[$i][0]
                    ];
                }
            }elseif ($row->data_type == 2){
                $arr = explode(",",$row->sn);
                foreach ($arr as $key => $val){
                    $list[] = [
                        "sn" => $val
                    ];
                }
            }elseif ($row->data_type == 3){
                $arr = explode(",",$row->sn);
                foreach ($arr as $key => $val){
                    $list[] = [
                        "sn" => $val
                    ];
                }
            }
        }
        $this->view->assign("row", $list);
        return $this->view->fetch();
    }

    public function check($ids){
        $row = $this->model->get($ids);

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $confirmType = $this->request->post('confirm_type');
        $confirmContent = $this->request->post('confirm_content');

        if($confirmType == 1){
            $data = [];//调拨数据
            $stocksData = [];//库存数据
            if($row->data_type == 1){
                $fileData = Tools::importExcel($row->file_url);
                for($i = 1;$i < count($fileData);$i++){
                    $sn = trim($fileData[$i][0]);
                    if($row->type == 1){
                        $equip = Lib::getAllocationBySn($sn,$row->id);
                        if($equip){
                            $this->error("设备：{$sn}已入库！");
                        }
                    }
                    $data[] = [
                        "allocation_id" => $row->id,
                        "sn" => $sn
                    ];
                    $stocksData[] = $sn;
                }
            }elseif ($row->data_type == 2){
                $list = explode(",",$row->sn);
                for($i = 0;$i < count($list);$i++){
                    $sn = $list[$i];
                    if($row->type == 1){
                        $equip = Lib::getAllocationBySn($sn,$row->id);
                        if($equip){
                            $this->error("设备：{$sn}已入库！");
                        }
                    }
                    $data[] = [
                        "allocation_id" => $row->id,
                        "sn" => $sn
                    ];
                    $stocksData[] = $sn;
                }
            }elseif ($row->data_type == 3){
                $list = explode(",",$row->sn);
                for($i = 0;$i < count($list);$i++){
                    $sn = $list[$i];
                    if($row->type == 1){
                        $equip = Lib::getAllocationBySn($sn,$row->id);
                        if($equip){
                            $this->error("设备：{$sn}已入库！");
                        }
                    }
                    $data[] = [
                        "allocation_id" => $row->id,
                        "sn" => $sn
                    ];
                    $stocksData[] = $sn;
                }
            }

            $policyId = $row->policy_id;
//            $policy = Lib::getPolicy($policyId);
//            if(!$policy){
//                $this->error("政策不存在，请联系上级！");
//            }

            Db::startTrans();
            try {
                //保存操作记录
                $row->confirm_type = 1;
                $row->confirm_time = time();
                $row->save();

                //调拨类型为订单，修改订单产品调拨状态
                if($row->type_enum == "order"){
                    $orderProduct = OrderProduct::where(['order_id' => $row->order_id,'product_id' => $row->product_id])->find();
                    $orderProduct->status = 2;
                    $orderProduct->save();
                }

                //保存调拨明细
                $details = new \app\common\model\AllocationDetails();
                $details->saveAll($data);

                //更新设备归属
                Tools::updateEquipInfo($data,$row->to_type,$row->to);

                //目标机构（代理）增加库存
                Tools::updateStocks($row->to_type,$row->to,$row->product_id,1,$stocksData,"设备调拨增加库存",$row->type);

                //减少调拨机构库存
                Tools::updateStocks($row->from_type,$row->from,$row->product_id,2,$stocksData,"设备调拨减少库存",$row->type);

                if($row->type == 1){
                    //政策关系表录入
                    $relationObj = Lib::getPolicyRelation($row->to_type,$row->to,$row->product_id,$policyId);
                    if(!$relationObj){
                        $relation = new PolicyRelation();
                        $relation->main_type = $row->to_type;
                        $relation->main_id = $row->to;
                        $relation->product_id = $row->product_id;
                        $relation->policy_id = $policyId;
                        $relation->save();
                    }
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error($e->getMessage());

            }
        }elseif ($confirmType == 2){
            $row->confirm_type = $confirmType;
            $row->confirm_content = $confirmContent;
            $row->confirm_time = time();
            $row->save();
        }

        $this->success("接收成功！");
    }

}
